//
//  WFDaquanRecipesViewController.m
//  WeiFang
//
//  Created by WeiFang Team on 2022.
//  Copyright © 2022 WeiFang Team. All rights reserved.
//

#import "WFDaquanRecipesViewController.h"

#import <WebKit/WebKit.h>

@interface WFDaquanRecipesViewController () <WKNavigationDelegate,WKScriptMessageHandler>

//webview,加载网页用。
@property (strong, nonatomic) WKWebView *webView;

@end

@implementation WFDaquanRecipesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.hidden = YES;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"延迟秒后打印出来的日志！");
        NSString *urlStr = [NSString stringWithFormat:@"%@?uuid=%@",kDaquanRecipesUrl,kUserManager.userManager.uuid];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
        [self.webView loadRequest:request];
        [self refreshData];
    });
}

- (void)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [SVProgressHUD dismiss];
}

/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [SVProgressHUD dismiss];
}

- (WKWebView *)webView{
    if (_webView == nil) {
        
        WKPreferences *pre = [[WKPreferences alloc] init];
        pre.javaScriptEnabled = YES;
        pre.javaScriptCanOpenWindowsAutomatically = YES;
        
        WKWebViewConfiguration *con = [[WKWebViewConfiguration alloc] init];
        con.preferences = pre;
        [con.preferences setValue:@(YES) forKey:@"allowFileAccessFromFileURLs"];
        con.allowsInlineMediaPlayback = YES;
        if (@available(iOS 10.0, *)) {
             [con setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
        }
        
        WKUserContentController* uc = [[WKUserContentController alloc] init];
        con.userContentController = uc;
        [uc addScriptMessageHandler:self name:@"webClose"];
        
        WKWebView *web = [[WKWebView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight) configuration:con];
        web.navigationDelegate = self;
        web.opaque = NO;
        web.backgroundColor = kViewBackgroundColor;
        [self.view addSubview:web];
        _webView = web;
    }
    return _webView;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"webClose"]) {
        [self backAction:nil];
    }
}

@end
